package com.topisv.tms.service.log;

import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import com.topisv.tms.entity.log.OrderLog;
import com.topisv.tms.repository.log.OrderLogDao;

/**
 * 订单日志_service
 * 
 * @author ch
 * 
 */
@Component
@Transactional(readOnly = true)
public class OrderLogService {

	@Autowired
	private OrderLogDao orderLogDao;
	
	/**
	 * 
	 * @param filterParams
	 * @param pageNumber 第几页
	 * @param pageSize  每页个数
	 * @return
	 */
	public Page<OrderLog> pageOrderLog(int pageNumber, int pageSize) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize);
		Specification<OrderLog> ar = buildSpecification();
		return orderLogDao.findAll(ar, pageRequest);
	}
	
	private Specification<OrderLog> buildSpecification() {
		return new Specification<OrderLog>(){
			@Override
			public Predicate toPredicate(Root<OrderLog> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				Predicate pre = cb.conjunction();
				pre.getExpressions().add(cb.isNull(r.get("synchStatus")));
				
				return pre;
			}
			
		};
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pageSize) {
		return new PageRequest(pageNumber - 1, pageSize);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<OrderLog> buildSpecification(Map<String, Object> filterParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		Specification<OrderLog> ar = DynamicSpecifications.bySearchFilter(filters.values(), OrderLog.class);
		return ar;
	}

	/**
	 * 插入订单日志
	 * @param orderLog
	 */
	@Transactional(readOnly = false)
	public void saveOrderLog(OrderLog orderLog){
		this.orderLogDao.save(orderLog);
	}

	/**
	 * 查询日志
	 * @param orderno 订单编号
	 * @return
	 */
	public List<OrderLog> loadLogByOrderno(String orderno) {
		return this.orderLogDao.loadLogByOrderno(orderno);
	}
	
	/**
	 * 查询日志
	 * @param orderno 订单编号
	 * @return
	 */
	public List<OrderLog> loadLogByOrdernoAndOperateType(String orderno,String operateType) {
		return this.orderLogDao.loadLogByOrdernoAndOperateType(orderno,operateType);
	}

}